package com.tdam2011.grupo06.gui;

import java.util.Date;
import java.util.List;

import com.tdam2011.grupo06.R;
import com.tdam2011.grupo06.control.DatabaseHelper;
import com.tdam2011.grupo06.model.MensajeBob;
import com.tdam2011.grupo06.network.BobMessageParserSax;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class widgetProvider extends AppWidgetProvider {

	public static String ACTION_WIDGET_NEWMESSAGE = "NewMessage";
	public static String ACTION_WIDGET_NEXTMESSAGE = "NextMessage";
	public static String ACTION_WIDGET_PREVMESSAGE = "PreviousMessage";

	private static List<MensajeBob> listaMensajes;
	private static int msgNumber = 0;

	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {

		cargarMensajes(context);
		updateMessageShown(context);

		RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
				R.layout.widget_layout);

		// Creates all Intent object, and set an Action for each of them
		Intent newMsgIntent = new Intent(context, widgetProvider.class)
				.putExtra("msg", "Checking for new Messages").setAction(
						ACTION_WIDGET_NEWMESSAGE);

		Intent nextMsgIntent = new Intent(context, widgetProvider.class);
		nextMsgIntent.setAction(ACTION_WIDGET_NEXTMESSAGE);
		nextMsgIntent.putExtra("msg", "Showing Next Message");

		Intent prevMsgIntent = new Intent(context, widgetProvider.class);
		prevMsgIntent.setAction(ACTION_WIDGET_PREVMESSAGE);
		prevMsgIntent.putExtra("msg", "Showing Previous Message");

		PendingIntent newMsgPendingIntent = PendingIntent.getBroadcast(context,
				0, newMsgIntent, 0);

		PendingIntent nextMsgPendingIntent = PendingIntent.getBroadcast(
				context, 0, nextMsgIntent, 0);

		PendingIntent prevMsgPendingIntent = PendingIntent.getBroadcast(
				context, 0, prevMsgIntent, 0);

		remoteViews.setOnClickPendingIntent(R.id.widget_app,
				newMsgPendingIntent);
		remoteViews.setOnClickPendingIntent(R.id.widget_next,
				nextMsgPendingIntent);
		remoteViews.setOnClickPendingIntent(R.id.widget_prev,
				prevMsgPendingIntent);

		appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);

	}

	private void updateMessageShown(Context context) {
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
				R.layout.widget_layout);
		if (listaMensajes.isEmpty()) {
			msgNumber = 0;
			remoteViews.setTextViewText(R.id.widget_message,
					context.getString(R.string.empty_listMensajesNuevos));
			remoteViews.setTextViewText(R.id.widget_author, 
					context.getString(R.string.de));
		} else {
			remoteViews.setTextViewText(R.id.widget_message,
					listaMensajes.get(msgNumber).getContent());
			remoteViews.setTextViewText(R.id.widget_author, 
					context.getString(R.string.de)+" "+listaMensajes.get(msgNumber).getNombre());
		}
		
		ComponentName thisWidget = new ComponentName(context, widgetProvider.class);
		AppWidgetManager.getInstance(context).updateAppWidget(thisWidget, remoteViews);
	}

	@Override
	public void onReceive(Context context, Intent intent) {

		// v1.5 fix that doesn't call onDelete Action
		final String action = intent.getAction();
		if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
			final int appWidgetId = intent.getExtras().getInt(
					AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
			if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
				this.onDeleted(context, new int[] { appWidgetId });
			}
		} else {
			// check, if our Action was called
			Log.d("Widget", "Checking Action");

			if (intent.getAction().equals(ACTION_WIDGET_NEXTMESSAGE)) {
				Log.d("Widget", "Action: Next message");
				if((msgNumber+1)<listaMensajes.size()){
					msgNumber++;
				}
				updateMessageShown(context);
			} else if (intent.getAction().equals(ACTION_WIDGET_PREVMESSAGE)) {
				Log.d("Widget", "Action: Previous message");
				if(msgNumber>0){
					msgNumber--;
				}
				updateMessageShown(context);
			} else if (intent.getAction().equals(ACTION_WIDGET_NEWMESSAGE)) {
				Log.d("Widget", "Action: Get Messages");
				cargarMensajes(context);
				msgNumber = 0;
				updateMessageShown(context);
			} else {
				Log.d("Widget", "Action " + action + " not recognized.");
			}
			super.onReceive(context, intent);
		}
	}

	private void cargarMensajes(Context context) {
		Log.d("Widget", "Loading Messages from Database.");
		Toast.makeText(context, context.getText(R.string.loadingMensajes),
				Toast.LENGTH_SHORT).show();
		BobMessageParserSax bobMessageParserSax = new BobMessageParserSax();
		SharedPreferences myPreference = PreferenceManager
				.getDefaultSharedPreferences(context);
		Date aux;
		if (DatabaseHelper.getInstance(context).getMensajesBobCountRecibidos() == 0) {
			aux = new Date(0);
		} else {
			aux = DatabaseHelper.getInstance(context)
					.getLastMensajesBobRecibido(new MensajeBob()).getFecha();
		}
		Log.d("Widget",
				"Getting messages for user:["
						+ myPreference.getString("nombreUsuario", "")
						+ "] using password ["
						+ myPreference.getString("contrasenaUsuario", "") + "]");
		listaMensajes = bobMessageParserSax.parseMessages(
				myPreference.getString("nombreUsuario", ""),
				myPreference.getString("contrasenaUsuario", ""), aux);
		Log.d("Widget", "Total messages recived: " + listaMensajes.size());
		if(listaMensajes.size()>0){
			String msj = "Tienes "+listaMensajes.size();
			if (listaMensajes.size()==1) {
				msj=msj+" mensaje!!";
			}
			else{
				msj=msj+" mensajes!!";
			}
			Notification notification = new Notification(R.drawable.icon, msj, System.currentTimeMillis());
			Intent intent = new Intent(context, Main.class);
			intent.putExtra("widget", true);
			notification.setLatestEventInfo(context,"Bob Msn",msj,PendingIntent.getActivity(context,0,intent,0));
			notification.defaults |= Notification.DEFAULT_VIBRATE;
			notification.defaults |= Notification.DEFAULT_SOUND;
			notification.defaults |= Notification.DEFAULT_LIGHTS;
			((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(1, notification);
		}

	}

}
